<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
       <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
       <el-breadcrumb-item>活动管理</el-breadcrumb-item>
       <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20" class="demo-autocomplete">
        <el-col :span="12">
          <el-input placeholder="请输入内容"  clearable v-model="queryInfo.query" @clear="getusersList">
            <el-button slot="append" icon="el-icon-search" @click="getusersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="12">
            <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table  stripe :data="usersList" style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="用户名" ></el-table-column>
        <el-table-column prop="mobile" label="手机号" ></el-table-column>
        <el-table-column prop="email" label="email"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 状态插槽 -->
          <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="身份"></el-table-column>
        <el-table-column label="操作" width="180px">
           <template slot-scope="scope">
             <!-- 修改用户按钮 -->
              <el-button type="primary" icon="el-icon-edit" circle @click="OpenEditDialog(scope.row.id)"></el-button>
              <!-- 分配权限按钮 -->
              <el-tooltip :enterable="false" effect="dark" content="分配权限" placement="top-end">
                 <el-button type="warning" icon="el-icon-help" @click="setRole(scope.row)"  circle></el-button>
              </el-tooltip>
              <!-- 删除按钮 -->
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteUser(scope.row.id)"></el-button>
           </template>
        </el-table-column>
      </el-table>
    </el-card>
<!-- ---------------------------------------------外面----------------------------------- -->
    <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[1, 2, 5, 10]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

    <!-- 添加用户对话框 -->
      <!-- 标题 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="dialogClose">
     <!-- 内容 -->
     <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
       <el-form-item label="用户名" prop="username"><el-input v-model="addForm.username"></el-input></el-form-item>
       <el-form-item label="密码" prop="password"><el-input v-model="addForm.password"></el-input></el-form-item>
       <el-form-item label="email" prop="email"><el-input v-model="addForm.email"></el-input></el-form-item>
       <el-form-item label="手机号" prop="mobile"><el-input v-model="addForm.mobile"></el-input></el-form-item>
     </el-form>
     <!-- 尾巴 -->
     <span slot="footer" class="dialog-footer">
     <el-button @click="dialogVisible = false">取 消</el-button>
     <el-button type="primary" @click="addUser">确 定</el-button>
     </span>
    </el-dialog>

    <!-- 修改用户  对话框 -->
      <!-- 标题 -->
    <el-dialog title="修改" :visible.sync="editDialog" width="50%" @close="editDialogClose" >
     <!-- 内容 -->
     <el-form :model="editForm" :rules="editRules" ref="editRuleForm" label-width="100px">
       <el-form-item label="用户名" prop="username"><el-input v-model="editForm.username" disabled></el-input></el-form-item>
       <el-form-item label="email" prop="email"><el-input v-model="editForm.email"></el-input></el-form-item>
       <el-form-item label="手机号" prop="mobile"><el-input v-model="editForm.mobile"></el-input></el-form-item>
     </el-form>
     <!-- 尾巴 -->
     <span slot="footer" class="dialog-footer">
     <el-button @click="dialogVisible = false">取 消</el-button>
     <el-button type="primary"  @click="editUser">确 定</el-button>
     </span>
    </el-dialog>
    <!-- 分配权限  对话框 -->
    <el-dialog title="分配角色" :visible.sync="isShowSetRoleDialog" @close="setRoleDialogClosed">
      <el-form :model="setRoleForm" >
         <el-form-item label="用户名" >{{setRoleForm.username}}</el-form-item>
         <el-form-item label="角色名">{{setRoleForm.role_name}}</el-form-item>
      </el-form>
      <el-select v-model="selectValueRoleId" placeholder="请选择">
         <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button type="info" @click="isShowSetRoleDialog = false">取消</el-button>
          <el-button @click="commitSetRole">确定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    // email 验证
    const checkeEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('输入正确邮箱'))
    }
    // 手机号验证
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
      // const regMobile = /^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('手机不太对'))
    }
    return {
      queryInfo: {
        query: '',
        // 现在第几页
        pagenum: 1,
        // 显示多少项
        pagesize: 1
      },
      usersList: [],
      total: 0,
      // 是否显示对话框
      dialogVisible: false,
      editDialog: false,
      isShowSetRoleDialog: false,
      // 添加用户的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        moblie: ''
      },
      // 修改用户数据
      editForm: {},
      // 设置角色信息
      setRoleForm: {},
      roleList: [],
      // 下拉菜单选中的 value
      selectValueRoleId: '',
      // 规则
      rules: {
        username: [
          { required: true, message: '输入东西', trigger: 'blur' },
          { min: 3, max: 10, message: '3~10个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '输入东西', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
          // { min: 6, max: 15, message: '6~15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '输入邮箱', trigger: 'blur' },
          { validator: checkeEmail, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '输入6~15个字符的密码', trigger: 'blur' },
          { min: 6, max: 16, message: '6~15个字符', trigger: 'blur' }
        ]
      },
      editRules: {
        mobile: [
          { required: true, message: '输入东西', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
          // { min: 6, max: 15, message: '6~15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '输入邮箱', trigger: 'blur' },
          { validator: checkeEmail, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getusersList()
  },
  methods: {
    // 获取用户列表
    async getusersList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$Message.error('失败')
      }
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 每页多少条
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getusersList()
    },
    // 现在多少页
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getusersList()
    },
    // 改变用户状态
    async changeState (val) {
      console.log(val + 'val')
      const { data: res } = await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$Message.error('更新状态失败')
      }
      this.$Message.success('状态转换成功')
    },
    // 监听 对话框关闭 清空表单
    dialogClose () {
      this.$refs.ruleForm.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.ruleForm.validate(async valid => {
        // 预校验: 如果不通过就结束
        console.log(valid)
        if (!valid) return this.$Message.error('valid')
        // 发起添加用户请求
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        console.log(this.addForm)
        if (res.meta.status !== 201) { return this.$Message.error('添加用户失败') }
        this.$Message.success('添加用户成功')
        this.dialogVisible = false
        this.getusersList()
      })
    },
    // 修改用户
    async OpenEditDialog (id) {
      console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$Message.error('没有从id获取数据')
      this.editForm = res.data
      this.editDialog = true
    },
    // 修改用户对话框的关闭事件
    editDialogClose () {
      this.$refs.editRuleForm.resetFields()
    },
    // 提交修改的用户
    editUser () {
      this.$refs.editRuleForm.validate(async valid => {
        if (!valid) return this.$Message.error('修改失败,信息是' + valid)
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) return this.$Message.error('修改失败')
        // 更新数据列表
        this.getusersList()
        // 关闭对话框
        this.editDialog = false
        this.$Message.success('修改成功')
      })
    },
    // 删除用户提示
    async deleteUser (id) {
      const confirmInfo = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmInfo)
      if (confirmInfo !== 'confirm') return this.$Message.info('取消删除')
      const { data: res } = await this.$http.delete('users/' + id)
      console.log(id)
      console.log(res)
      if (res.meta.status !== 200) return this.$Message.error('法力值不足，删不掉')
      this.$Message.success('删掉了')
      this.getusersList()
    },
    // 设置角色
    async setRole (setRoleForm) {
      // console.log(1)
      this.isShowSetRoleDialog = true
      this.setRoleForm = setRoleForm
      // console.log(this.setRoleForm)
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$Message.error('没有角色信息')
      this.roleList = res.data
      // console.log(this.roleList)
    },
    // 提交角色分配
    async commitSetRole () {
      if (!this.selectValueRoleId) return this.$Message.error('选择要分配的角色')
      const { data: res } = await this.$http.put(`users/${this.setRoleForm.id}/role`, { rid: this.selectValueRoleId })
      if (res.meta.status !== 200) return this.$Message.error('先不要使用这个，失败 bilibili P439')
      this.$Message.success('给角色成功')
      this.getusersList()
      this.isShowSetRoleDialog = false
    },
    // 关闭 分配角色对话框
    setRoleDialogClosed () {
      this.selectValueRoleId = ''
      this.setRoleForm = {}
    }
    // ----
  }
}
</script>
<style lang="less" scoped>

</style>
